﻿#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>

// 采样参数
const double PI = 3.14159265358979323846;
const double freq = 1000.0; // 信号频率 1kHz
const double duration = 0.005; // 信号时长 5ms
const double amp = 1.0;

// 生成原始信号
std::vector<double> generate_signal(double fs, double duration, double freq) {
    int N = static_cast<int>(fs * duration);
    std::vector<double> signal(N);
    for (int n = 0; n < N; ++n) {
        signal[n] = amp * sin(2 * PI * freq * n / fs);
    }
    return signal;
}

// 采样
std::vector<double> sample_signal(const std::vector<double>& signal, double fs_orig, double fs_sample) {
    int N = static_cast<int>(fs_sample * duration);
    std::vector<double> samples(N);
    for (int n = 0; n < N; ++n) {
        int idx = static_cast<int>(n * fs_orig / fs_sample);
        if (idx < signal.size())
            samples[n] = signal[idx];
        else
            samples[n] = 0;
    }
    return samples;
}

// 零阶保持重建
std::vector<double> reconstruct_signal(const std::vector<double>& samples, double fs_sample, double fs_recon) {
    int N = static_cast<int>(fs_recon * duration);
    std::vector<double> recon(N);
    for (int n = 0; n < N; ++n) {
        int idx = static_cast<int>(n * fs_sample / fs_recon);
        if (idx < samples.size())
            recon[n] = samples[idx];
        else
            recon[n] = 0;
    }
    return recon;
}

// 导出数据到csv，便于用Python等工具画图
void export_csv(const std::string& filename, const std::vector<double>& data, double fs) {
    std::ofstream file("H://" + filename); // 修改为保存到H盘
    for (size_t i = 0; i < data.size(); ++i) {
        file << i / fs << "," << data[i] << "\n";
    }
    file.close();
}
int main() {
    double fs_orig = 50000.0; // 原始信号采样率 50kHz
    auto orig = generate_signal(fs_orig, duration, freq);

    // 情况1：采样率大于2倍最高频率
    double fs_high = 2500.0; // 2.5kHz
    auto samples_high = sample_signal(orig, fs_orig, fs_high);
    auto recon_high = reconstruct_signal(samples_high, fs_high, fs_orig);

    // 情况2：采样率小于2倍最高频率
    double fs_low = 1500.0; // 1.5kHz
    auto samples_low = sample_signal(orig, fs_orig, fs_low);
    auto recon_low = reconstruct_signal(samples_low, fs_low, fs_orig);

    // 导出数据
    export_csv("H://orig.csv", orig, fs_orig);
    export_csv("H://recon_high.csv", recon_high, fs_orig);
    export_csv("H://recon_low.csv", recon_low, fs_orig);

    std::cout << "数据已导出为 orig.csv, recon_high.csv, recon_low.csv\n";
    std::cout << "请用Python或Excel等工具画图对比。\n";
    return 0;
}